package com.mdata.service;

import com.mdata.common.*;
import com.mdata.model.dto.wechat.result.AccessTokenResult;
import com.mdata.model.po.SubjectUser;
import com.mdata.utils.RedisUtil;
import lombok.extern.slf4j.Slf4j;
import org.apache.shiro.SecurityUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.LinkedMultiValueMap;
import org.springframework.util.MultiValueMap;
import org.springframework.web.client.RestTemplate;
import org.springframework.web.util.UriComponentsBuilder;

import java.util.Objects;

@Slf4j
@Service
public class CommonService {

    @Autowired
    public RestTemplate restTemplate;
    public static String WECHAT_MANAGE_URL = "https://qyapi.weixin.qq.com/cgi-bin/";



    /**
     * 获取access_token
     * 注意事项：
     * 开发者需要缓存access_token，用于后续接口的调用（注意：不能频繁调用gettoken接口，否则会受到频率拦截）。当access_token失效或过期时，需要重新获取。
     *
     * access_token的有效期通过返回的expires_in来传达，正常情况下为7200秒（2小时），有效期内重复获取返回相同结果，过期后获取会返回新的access_token。
     * 由于企业微信每个应用的access_token是彼此独立的，所以进行缓存时需要区分应用来进行存储。
     * access_token至少保留512字节的存储空间。
     * 企业微信可能会出于运营需要，提前使access_token失效，开发者应实现access_token失效时重新获取的逻辑。
     * https://work.weixin.qq.com/api/doc/90000/90135/91039
     * @param corpSecret 客户联系、会话存档、自建应用 secret
     * @return
     */
    public AccessTokenResult getToken(String corpSecret){
//        SubjectUser subjectUser = (SubjectUser) SecurityUtils.getSubject().getPrincipal();

        String key = RedisKeyConstant.WECHAT_MANAGE_ACCESS_TOKEN + getWechatCorpId() + ":" + corpSecret;
        if(RedisUtil.hasKey(key)){
            return (AccessTokenResult) RedisUtil.get(key);
        }
        MultiValueMap<String, String> queryParamMap = new LinkedMultiValueMap<>();
        queryParamMap.add("corpid", getWechatCorpId());
        queryParamMap.add("corpsecret", corpSecret);
        AccessTokenResult accessTokenResult = BaseRestRequest.getForObject(restTemplate,
                WECHAT_MANAGE_URL + "gettoken", queryParamMap, AccessTokenResult.class);
        if(!Objects.equals(accessTokenResult.getErrCode(), CommonCodeConstant.SUCCESS_CODE)){
            throw new DefinitionException(ResponseEnum.WECHAT_ERROR_ACCESS_TOKEN.getCode(), accessTokenResult.getErrMsg());
        }
        RedisUtil.set(key, accessTokenResult, accessTokenResult.getExpiresIn());
        return accessTokenResult;
    }

    /**
     * url 拼接 access_token
     * @param secret
     * @param url
     * @return
     */
    public String splicingAccessToken(String secret, String url){
        MultiValueMap<String, String> map = new LinkedMultiValueMap<>();
        map.add("access_token", getToken(secret).getAccessToken());
        UriComponentsBuilder builder = UriComponentsBuilder.fromHttpUrl(WECHAT_MANAGE_URL + url).queryParams(map);
        return builder.toUriString();
    }

    public String splicingAccessToken(String secret, String url, MultiValueMap<String, String> queryParamMap){
        queryParamMap.add("access_token", getToken(secret).getAccessToken());
        UriComponentsBuilder builder = UriComponentsBuilder.fromHttpUrl(WECHAT_MANAGE_URL + url).queryParams(queryParamMap);
        return builder.toUriString();
    }

    public String getWechatCorpId(){
        return "ww689e7f7396dd4ba7"; // 铀媒科技
    }

    public String getWechatCustomerContactSecret(){
        return "QvK7PGdiFkc5vCzqzuo9BpoD1j-dIVj7dEegMYbTXXA"; // 铀媒科技
    }

    public String getWechatAddressBookSecret(){
        return "755jGYXZVDwNSnW6IvcHDOjExa-Uw7Zm-0h2syxFTFE"; // 铀媒科技
    }

    public String getWechatManageSecret(){
        return "x8ss5QoMBb45q3IKUfbuEvM3Kwzagcf0sR9rvaVGNDY"; // 铀媒科技
    }

    public String getWechatSessionArchivingSecret(){
        return "";
    }

//    public String getWechatCorpId(){
//        SubjectUser subjectUser = (SubjectUser) SecurityUtils.getSubject().getPrincipal();
//        return subjectUser.getWechatCorpId();
//    }
//
//    public String getWechatCustomerContactSecret(){
//        SubjectUser subjectUser = (SubjectUser) SecurityUtils.getSubject().getPrincipal();
//        return subjectUser.getWechatCustomerContactSecret();
//    }
//
//    public String getWechatAddressBookSecret(){
//        SubjectUser subjectUser = (SubjectUser) SecurityUtils.getSubject().getPrincipal();
//        return subjectUser.getWechatAddressBookSecret();
//    }
//
//    public String getWechatManageSecret(){
//        SubjectUser subjectUser = (SubjectUser) SecurityUtils.getSubject().getPrincipal();
//        return subjectUser.getWechatManageSecret();
//    }
//
//    public String getWechatSessionArchivingSecret(){
//        SubjectUser subjectUser = (SubjectUser) SecurityUtils.getSubject().getPrincipal();
//        return subjectUser.getWechatSessionArchivingSecret();
//    }
}
